package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"fresh-box/models/cache"
	"fresh-box/models/mysql"
	"time"

	"fresh-box/freshrpc/freshrpc"
	"fresh-box/freshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshListLogic {
	return &FreshListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FreshListLogic) FreshList(in *freshrpc.FreshListRequest) (*freshrpc.FreshListResponse, error) {
	// todo: add your logic here and delete this line

	var fresh []mysql.FreshClass

	key := "freshList"
	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		mysql.DB.Debug().Model(&mysql.Fresh{}).
			Select("fresh.*classes.`name` as class_name").
			Joins("left join classes on freshes.class_id = classes.id").
			Find(&fresh)

		marshal, _ := json.Marshal(fresh)
		cache.Rdb.Set(l.ctx, "freshList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &fresh)
	}

	var freshLists []*freshrpc.FreshList
	for _, class := range fresh {
		list := freshrpc.FreshList{
			Name:      class.Name,
			Price:     float32(class.Price),
			Stock:     class.Stock,
			Image:     class.Image,
			Info:      class.Info,
			ClassName: "",
			FreshId:   int64(class.ID),
		}
		freshLists = append(freshLists, &list)
		fmt.Println(freshLists)
	}

	return &freshrpc.FreshListResponse{
		List: freshLists,
	}, nil
}
